from utils.baseResource import BaseResource, DataResource
from utils.db_seesion import fetch_to_dict, execute
from utils.Response import response
from flask_restful import reqparse
from werkzeug.security import generate_password_hash, check_password_hash
from utils.tools import validateEmail
import datetime
# from flask_mail import Message
from init import mail as sendmail, redis_store
from utils.authenticate import token_md5


class User(BaseResource):
    paser = reqparse.RequestParser()
    paser.add_argument('username', required=True, help='username is required')
    paser.add_argument('password', required=True, help='password is required')
    paser.add_argument('nickname', required=True, help='nickname is required')
    paser.add_argument('mail', required=True, help='mail is required')

    def post(self):
        User.paser.parse_args()
        sql = 'select role from users where id=:user_id'
        role_result = fetch_to_dict(sql=sql, params={'user_id': self._user_id}, fecth='one')
        if role_result:
            print(role_result.get('role'))
            if role_result.get('role') != 1:
                return response(code=1001, msg='没有权限创建')
        else:
            return response(code=1001, msg='系统好像出问题了')
        mail = self._datas.get('mail')
        if validateEmail(mail) != 1:
            return response(code=1001, msg='邮箱格式错误')
        username = self._datas.get('username')
        sql_check_username = 'select username from users where username=:username'
        check_user_result = fetch_to_dict(sql=sql_check_username, params={'username': username}, fecth='one')
        if check_user_result:
            return response(code=1001, msg='用户名存在')
        password = generate_password_hash(self._datas.get('password'))
        nickname = self._datas.get('nickname')
        icon = self._datas.get('icon',
                               'https://raw.githubusercontent.com/taylorchen709/markdown-images/master/vueadmin/user.png')
        create_time = datetime.datetime.now()
        update_time = datetime.datetime.now()
        sql_add_user = 'insert into users(username,password,nickname,icon,create_time,update_time,mail) values(:username,:password,:nickname,:icon,:create_time,:update_time,:mail)'
        execute(sql=sql_add_user,
                params={'username': username, 'password': password, 'icon': icon, 'create_time': create_time,
                        'update_time': update_time, 'mail': mail, 'nickname': nickname})
        # send email
        # msg = Message('用户创建成功通知', sender='gongnanxiong235@126.com', recipients=[mail])
        # msg.html = '<h3>尊敬的<span style="color: red">%s</span>帅哥/美女:</h3><div>您的账号已经创建成功，请妥善保管您的密码,祝你使用愉快~</div>' % username
        # sendmail.async_send_mail(msg)
        return response(msg='创建用户成功')


class Login(DataResource):
    paser = reqparse.RequestParser()
    paser.add_argument('username', required=True, help='username is required')
    paser.add_argument('password', required=True, help='password is required')

    def post(self):
        Login.paser.parse_args()
        username = self._datas.get('username')
        password = self._datas.get('password')
        user = fetch_to_dict(
            'select id as user_id, password,role,nickname,icon from users where username=:username and is_delete=0',
            {'username': username}, fecth='one')
        if not user:
            return response(code=1001, msg='用户名不存在')
        if check_password_hash(user.get('password'), password):
            user.pop('password')
            token = token_md5(password)
            user['token'] = token
            user_id = user.get('user_id')
            redis_store.hset('platformLogin', user_id, token)
            print(user)
            return response(data=user)
        return response(code=1002, msg='密码错误')


class LoginOut(BaseResource):
    def get(self):
        redis_store.hdel('platformLogin', self._user_id)
        return response()
